package com.macro.mall.portal.controller;

import com.macro.mall.common.api.CommonResult;
import com.macro.mall.domain.UploadResult;
import com.macro.mall.model.SmsHomeAdvertise;
import com.macro.mall.portal.service.PmsAlbumPicService;
import com.macro.mall.portal.service.SmsHomeAdvertiseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@Api(tags = "PmsAlbumPic", description = "文件上传")
@RequestMapping("/pic/file")
public class PmsAlbumPicController {
    @Autowired
    private PmsAlbumPicService pmsAlbumPicServiceImpl;
    @Autowired
    private SmsHomeAdvertiseService smsHomeAdvertiseService;

    @ApiOperation("商品图片上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ApiImplicitParam(name = "type", value = "待定", required = false, paramType = "query", dataType = "String")
    private CommonResult<UploadResult> uploadFile(HttpServletRequest request,
                                                  HttpServletResponse response,
                                                  @RequestParam(value = "type", required = false) String type) throws Exception {
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            if ("1".equals(type)) {
                UploadResult uploadResult = smsHomeAdvertiseService.uploadFile(multiRequest);
                return CommonResult.success(uploadResult);
            } else {
                return CommonResult.success(pmsAlbumPicServiceImpl.uploadFile(multiRequest));
            }
        }
        return CommonResult.failed();
    }
}
